package com.sayi.dzapi.controller;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.util.HashMap;

import com.sayi.dzapi.utils.JwtUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RestController
public class PostController{
    
    private static final Logger log = LoggerFactory.getLogger(UserService.class);
    
    @Autowired
    private JdbcTemplate jdbcTemplate;


    @GetMapping("/posts")
    public List<Map<String, Object>> getPosts(@RequestParam(value = "tid") Integer tid) {
        String sql;
        if (tid != null) {
            sql = "SELECT * FROM pre_forum_post WHERE tid = ?";
            List<Map<String, Object>> posts = jdbcTemplate.queryForList(sql, tid);
            for(Map<String, Object> post:posts){
                boolean hasAttachment = (boolean) post.get("attachment");
                if(hasAttachment){
                    String getAttachment = "SELECT * FROM pre_forum_attachment WHERE tid = ?";
                    List<Map<String,Object>> attachments=jdbcTemplate.queryForList(getAttachment,tid);

                    for(Map<String,Object> attachment:attachments){
                        int tableId = (int) attachment.get("tableid");
                        long aid = (long) attachment.get("aid");
                        log.info("tableId:"+tableId+",aid:"+aid);
                        String getAttachmentUrl = "SELECT attachment FROM pre_forum_attachment_"+tableId+" WHERE aid = ?";
                        try{
                            String url=(String)jdbcTemplate.queryForObject(getAttachmentUrl,String.class,aid);
                            attachment.put("url",url);
                        }catch(Exception e){
                            attachment.put("url",e.getMessage());
                        }
                    }
                    post.put("attachments",attachments);
                }
            }
            return posts;
        } else {
            // 抛出异常，Spring MVC 会将其转换为 400 Bad Request 响应
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "tid parameter is required");
        }
    }
    
    

    @PostMapping("/post_comment")
    public ResponseEntity<String> postComment(
            @RequestParam("tid") int tid,
            @RequestParam("message") String message,
            @RequestHeader(value="Authorization",required=false) String authorizationHeader) {
        // Step 1: 从请求头获取 Authorization 信息 (格式：Bearer <token>)
        if(authorizationHeader==null){
            return ResponseEntity.ok("missing auth");
        }
        if(!authorizationHeader.startsWith("Bearer ")){
            return ResponseEntity.ok("error auth");
        }
        String token = null;
        if (authorizationHeader.startsWith("Bearer ")) {
            token = authorizationHeader.substring(7);  // 去除 "Bearer " 前缀
        }
        int userId=JwtUtil.extractUserId(token);

        String username=JwtUtil.extractUsername(token);
        // Step 2: 验证 JWT Token 是否有效
        /*if (token == null || !JwtUtil.validateToken(token,userId)) {
            return ResponseEntity.status(401).body("Unauthorized: Invalid or missing token.");
        }*/

        if(token == null){
            return ResponseEntity.status(401).body("Unauthorized: Missing token.");
        }else if(!JwtUtil.validateToken(token,userId)){
            return ResponseEntity.status(401).body("Unauthorized: Invalid token.");
        }

        String checkThreadSql = "SELECT COUNT(*) FROM pre_forum_thread WHERE tid = ?";
        int postCount = jdbcTemplate.queryForObject(checkThreadSql, Integer.class, tid);
        
        if (postCount == 0) {
            return ResponseEntity.status(404).body("Thread not found: The specified thread does not exist.");
        }


        // 查询pre_forum_post表中tid的最大值
        String maxPidSql = "SELECT MAX(pid) FROM pre_forum_post";
        Integer maxPid = jdbcTemplate.queryForObject(maxPidSql, Integer.class);

        // 如果表中没有帖子，maxTid将为null，需要将其设置为0
        int pid = (maxPid != null) ? maxPid + 1 : 1;


        // 查询当前tid下position的最大值
        String maxPositionSql = "SELECT MAX(position) FROM pre_forum_post WHERE tid = ?";
        Integer maxPosition = jdbcTemplate.queryForObject(maxPositionSql, Integer.class, tid);

        // 如果表中没有帖子，maxPosition将为null，需要将其设置为0
        int position = (maxPosition != null) ? maxPosition + 1 : 1;

        //获取发帖时间
        long time=System.currentTimeMillis()/1000;
        // 假设我们有一个插入评论的SQL语句
        String sql = "INSERT INTO pre_forum_post (pid, tid, premsg, message, position, author, authorid, dateline) VALUES (?, ?, '', ?, ?, ?, ?, ?)";
        
        // 执行插入操作
        int result = jdbcTemplate.update(sql, pid, tid, message, position, username, userId, time);
        
        // 根据结果返回相应的响应
        if (result > 0) {
            String updateCountSql = "UPDATE pre_forum_thread SET replies = replies + 1 WHERE tid = ?";
            int updatedRows = jdbcTemplate.update(updateCountSql, tid);


            return ResponseEntity.ok("Comment posted successfully.");
        } else {
            return ResponseEntity.badRequest().body("Failed to post comment.");
        }
    }
}